//
//  AppDelegate.m
//  quickBatchManager
//
//  Created by jack on 15/9/15.
//  Copyright (c) 2015年 jack. All rights reserved.
//

#import "AppDelegate.h"

@interface AppDelegate ()
{
    BOOL isSync;
    BOOL isSyncImage;
}

@end

@implementation AppDelegate
@synthesize opType;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    
    [self initUserDefaults];
    
    isSync = NO;
    isSyncImage = NO;
    //1.网络小菊花
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    //2.监控网络状态
    [self startNetworkMonitoring];
    
    //7.创建APP缓存目录
    NSArray *paths = DOCUMENT_PATH;
    NSString *photoCacheDir = [[paths objectAtIndex:0] stringByAppendingPathComponent:folerName_PHOTO];
    NSString *dataCacheDir = [[paths objectAtIndex:0] stringByAppendingPathComponent:folerName_Data];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    [fileManager createDirectoryAtPath:photoCacheDir withIntermediateDirectories:YES attributes:nil error:nil];
    [fileManager createDirectoryAtPath:dataCacheDir withIntermediateDirectories:YES attributes:nil error:nil];
    
    
    //.数据更新通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(eventSynchronization:)
                                                 name:EventSynchronization object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(eventImageSynchronization:)
                                                 name:EventImageSynchronization object:nil];
    
    netService = [[NetService alloc] init];
  
    _homeVc=[[HomeViewController alloc] init];
    self.window.rootViewController = _homeVc;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //分享
    [UMSocialData setAppKey:UM_KEY];
    [UMSocialWechatHandler setWXAppId:@"wx91d7e1fa73e5fcd2" appSecret:@"b72ad7bd8e40aa391ce7a6751d6f0e91" url:@"http://www.umeng.com/social"];
    
    return YES;
}


-(void)eventSynchronization:(NSNotification *)notifiation
{
    AFNetworkReachabilityManager *mgr=[AFNetworkReachabilityManager sharedManager];
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            if(mgr.isReachableViaWiFi)
            {
                BACK((^{
                    NSArray *syncDatas =[UploadData searchWithWhere:nil];
                    for (UploadData *data in syncDatas) {
                        if(mgr.isReachableViaWiFi)
                        {
                            NSLog(@"上传数据");
                            NSMutableDictionary *params = [NSMutableDictionary dictionary];
                            [params setObject:AK_USRE forKey:@"ak"];
                            [params setObject:data.t_table forKey:@"table"];
                            [params setObject:data.t_pkName forKey:@"pk"];
                            [params setObject:[NSString stringWithFormat:@"%ld",data.t_opType] forKey:@"opType"];
                            [params setObject:data.content forKey:@"content"];
                            [netService post:SYNC_DB_URL params:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                [data deleteToDB];
                                NSLog(@"上传数据成功:%@",responseObject);
                            } fail:^(AFHTTPRequestOperation *operation, NSError *error) {
                                NSLog(@"上传数据失败:%@",[error localizedDescription]);
                            }];
                        }else
                        {
                            [netService stopAllOperations];
                        }
                        
                    }
                    
                }));
                
            }
        });
    
    
}


-(void)eventImageSynchronization:(NSNotification *)notifiation
{
        AFNetworkReachabilityManager *mgr=[AFNetworkReachabilityManager sharedManager];
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
        if(mgr.isReachableViaWiFi)
        {
            
            BACK(^{
                
                NSMutableArray *products = [ProductModel searchWithWhere:@"isImageUpload=0"];       
                for (int i=0; i<products.count; i++) {
                    if(mgr.isReachableViaWiFi)
                    {
                    ProductModel *model = [products objectAtIndex:i];
                    NSMutableDictionary *params = [NSMutableDictionary dictionary];
                    //[params setObject:AK_USRE forKey:@"ak"];
                    UIImage *image = [UIImage imageNamed:[ToolUtils getImageLocalPath:model.photo]];
                    NSString *imageName = [ToolUtils getImageLocalPath:model.photo];
                    NSRange range = [imageName  rangeOfString:@"/" options:NSBackwardsSearch];
                    imageName  =  [imageName substringFromIndex:range.location+1];
                    NSLog(@"imageName:%@",imageName);
                    [netService post:UPLOAD_IMAGE_URL params:params filedName:@"file" imageName:imageName image:image success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         NSLog(@"上传图片成功");
                     //   model.isImageUpload = YES;
                        //[model updateToDB];
                    } fail:^(AFHTTPRequestOperation *operation, NSError *error) {
                         NSLog(@"上传图片失败");
                    }];
                    
                    }
                }
    
                
            });
            
        }
    });
    
}


/**
 *	@brief	开始检测网络状态
 */
-(void)startNetworkMonitoring
{
    AFNetworkReachabilityManager *mgr=[AFNetworkReachabilityManager sharedManager];
    //当网络状态改变的时候，就会调用
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown://未知网络
            case AFNetworkReachabilityStatusNotReachable://没有网络
                NSLog(@"没有网络（断网）");
                isSync = NO;
                isSyncImage  = NO;
                // [self showAlertView:@"提示" message:@"网络异常，请检查网络设置！"];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN://手机自带网络
                NSLog(@"手机自带网络");
                isSync = NO;
                isSyncImage  = NO;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi://WIFI
                NSLog(@"WIFI");
                isSync = YES;
                isSyncImage  = YES;
               [[NSNotificationCenter defaultCenter] postNotificationName:EventSynchronization object:nil];
               // [[NSNotificationCenter defaultCenter] postNotificationName:EventImageSynchronization object:nil];
                break;
        }
    }];
    //开始监控
    [mgr startMonitoring];
}




- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
    }
    return result;
}


////收到本地通知
//-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
//{
//    
//}

//#if __IPAD_OS_VERSION_MAX_ALLOWED >= __IPAD_6_0
//- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
//{
//    return UIInterfaceOrientationMaskAll;
//}
//#endif


- (void) initUserDefaults
{
    //设置NSUserDefaults默认值
    NSMutableDictionary *defaultValues=[[NSMutableDictionary alloc] init];
    [defaultValues setObject:@"现金|支付宝|微信|银行卡|汇款" forKey:NSDEFAULT_ST_PAYMENT];
    [defaultValues setObject:@"NO" forKey:NSDEFAULT_ST_PAYMENT_DS];

    
    [[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
